package com.stockz.indicator.movingAverage.simple;

import java.util.List;

import com.stockz.core.model.Bar;
import com.stockz.core.util.BarUtil.BarValueType;
import com.stockz.core.util.ListUtil;
import com.stockz.indicator.Indicator;

public class SimpleMovingAverageIndicator implements Indicator<SimpleMovingAverageIndicatorConfiguration> {
	
	private SimpleMovingAverageIndicatorConfiguration simpleMovingAverageIndicatorConfiguration
	= new SimpleMovingAverageIndicatorConfiguration();
	private BarValueType barValueType = BarValueType.AVGPRICE;
	
	@Override
	public double getValue(List<Bar> barList) {
		int span = simpleMovingAverageIndicatorConfiguration.getSpan();
		if(barList == null || barList.isEmpty() || barList.size() <= span){
			return 0;
		}
		
		BarValueType barValueType = getBarValueType();
		double[] values = ListUtil.convert(barList,barValueType,span);
		double sum = 0;
		for(double value : values){
			sum += value;
		}
		return sum/values.length;
	}

	@Override
	public double[] getValues(List<Bar> barList) {
		int span = simpleMovingAverageIndicatorConfiguration.getSpan();
		double[] barValues = ListUtil.convert(barList, barValueType);
		double[] values = new double[barList.size()];
		double sum = 0;
		for(int i = barList.size()-1; i >=0; i--){
			if(barValues[i] == 0){
				continue;
			}
			if(i > barList.size() - span){
				values[i] = 0;
			}else if(i ==  barList.size() - span){
				values[i] = sum/span;
			}else{
				values[i] = sum/span;
				sum -= barValues[i+span];
			}
			sum += barValues[i];
		}
		return values;
	}
	
	@Override
	public SimpleMovingAverageIndicatorConfiguration getIndicatorConfiguration() {
		return simpleMovingAverageIndicatorConfiguration;
	}

	public BarValueType getBarValueType() {
		return barValueType;
	}

	public void setBarValueType(BarValueType barValueType) {
		this.barValueType = barValueType;
	}
}
